<?php

if (!defined('BASEPATH'))
    exit('Vui lòng liên hệ nhatnv');

class MY_Controller extends CI_Controller {

    public $_data;

    public function __construct() {
        parent::__construct();
       // die(base_url(uri_string())."kajsdhkh");
        //$this->outpdie(base_url(uri_string())."kajsdhkh");ut->cache(5);
        //$this->output->enable_profiler(TRUE);
        $this->load->helper(array('url', 'text', 'form'));
        $this->load->library(array('session'));
        $this->data['baseurl'] = site_url();
        $this->data['fview'] = new Ultility;
    }

    //Ham cat chuoi khong mat chu
    private function substr($str, $length, $minword = 3) {
        $sub = '';
        $len = 0;
        foreach (explode(' ', $str) as $word) {
            $part = (($sub != '') ? ' ' : '') . $word;
            $sub .= $part;
            $len += strlen($part);
            if (strlen($word) > $minword && strlen($sub) >= $length) {
                break;
            }
        }
        return $sub . (($len < strlen($str)) ? '...' : '');
    }

    public function get_ascii($st) {
        $vietChar = 'á|à|ả|ã|ạ|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ|é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|ó|ò|ỏ|õ|ọ|ơ|ớ|ờ|ở|ỡ|ợ|ô|ố|ồ|ổ|ỗ|ộ|ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|í|ì|ỉ|ĩ|ị|ý|ỳ|ỷ|ỹ|ỵ|đ|Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẵ|Ặ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ|É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ|Ó|Ò|Ỏ|Õ|Ọ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự|Í|Ì|Ỉ|Ĩ|Ị|Ý|Ỳ|Ỷ|Ỹ|Ỵ|Đ';
        $engChar = 'a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|e|e|e|e|e|e|e|e|e|e|e|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|u|u|u|u|u|u|u|u|u|u|u|i|i|i|i|i|y|y|y|y|y|d|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|E|E|E|E|E|E|E|E|E|E|E|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|U|U|U|U|U|U|U|U|U|U|U|I|I|I|I|I|Y|Y|Y|Y|Y|D';
        $arrVietChar = explode("|", $vietChar);
        $arrEngChar = explode("|", $engChar);
        $ftc = strtolower(str_replace($arrVietChar, $arrEngChar, $st));
        $vowels = array("-", " -", "- ", " ", "/", "+", "=", "{", "}", ")", "(", "!", "`", "'", "~", "@", "#", "$", "%", "^", "&", "*", "_", "!", "!", ".", ",", ";", ":", "]", "[", "/");
        return str_replace($vowels, ' ', $ftc);
    }

    public function printstr($str, $len) {
        $arrstr = explode(" ", $str);
        $detail = "";
        $return = "";
        if (count($arrstr) <= $len)
            $len = count($arrstr);
        else {
            $detail = " ...";
        }
        for ($i = 0; $i < $len; $i++) {
            $return .= $arrstr[$i] . " ";
        }

        return $return . '...';
    }

    public function checkAdmin($id) {
        if (in_array($id, array(null, '', '0'))) {
            redirect('user/login');
        }
        $db = $this->db->query('SELECT id FROM user WHERE id = ' . $id . ' AND level = 1')->num_rows();
        if ($db == 0) {
            redirect('user/login');
        }
    }

    /* GET PARAM */

    public function getParamString($param) {
        return addslashes(isset($_REQUEST[$param]) ? $this->security->xss_clean($_REQUEST[$param]) : '');
    }

    public function getParamArray($param) {
        return isset($_REQUEST[$param]) ? $this->security->xss_clean($_REQUEST[$param]) : '';
    }

    public function getParamInt($param) {
        return intval(isset($_REQUEST[$param]) ? $this->security->xss_clean($_REQUEST[$param]) : '');
    }

    public function getParamUrl($id) {
        return intval($this->decode_id($this->security->xss_clean($this->uri->segment($id))));
    }

    public function getParamGet($param, $type) {
        if ($type == '1') {
            return intval($this->security->xss_clean($_GET[$param]));
        } else {
            return addslashes($this->security->xss_clean($_GET[$param]));
        }
    }

    public function getParamUri($id, $param) {
        if ($param == '1') {
            return intval($this->security->xss_clean($this->uri->segment($id)));
        } else if ($param == '3') {
            $param_ = $this->security->xss_clean($this->uri->segment($id));
            if (in_array($param_, array(null, '', '0'))) {
                return 0;
            }
            $data = explode('-', addslashes($param_));
            return $data[1];
        } else {
            return addslashes($this->security->xss_clean($this->uri->segment($id)));
        }
    }

    /* Function get_contents_https */

    public function getSslPages($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function getSslPage($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function replace_url($var) {
        $vowels = array("-", "- ", " -", "--", "---", "/", "+", "=", "{", "}", ")", "(", "!", "`", "~", "@", "#", "$", "%", "^", "&", "*", "_", "!", "!", ".", ",", ";", ":", "]", "[");
        $var = str_replace($vowels, '', $var);
        return $val = str_replace(' ', '-', $var);
    }

    public function generateCode($length, $type = 0) {
        if ($type == 0) {
            $chars = "0123456789";
        } else {
            $chars = "0123456789ABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789ABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789STUVWXYZ0123456789ABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
        }
        $code = "";
        $clen = strlen($chars) - 1;
        while (strlen($code) < $length) {
            $code .= $chars[mt_rand(0, $clen)];
        }
        $salt = $code;
        return $salt;
    }

    public function get_client_ip() {
        foreach (array('HTTP_CLIENT_IP',
    'HTTP_X_FORWARDED_FOR',
    'HTTP_X_FORWARDED',
    'HTTP_X_CLUSTER_CLIENT_IP',
    'HTTP_FORWARDED_FOR',
    'HTTP_FORWARDED',
    'REMOTE_ADDR') as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $IPaddress) {
                    $IPaddress = trim($IPaddress); // Just to be safe

                    if (filter_var($IPaddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {

                        return $IPaddress;
                    }
                }
            }
        }
    }

    public function renderLink($arr) {

        $_chal = $arr->challenge;
        $hexchal = pack("H32", $_chal);
        $newchal = $arr->uamsecret ? pack("H*", md5($hexchal . $arr->uamsecret)) : $hexchal;
        $response = md5("\0" . $arr->password_fast . $newchal);

        $newpwd = pack("a32", $arr->password_fast);
        $pappassword = implode('', unpack("H32", ($newpwd ^ $newchal)));

        return 'http://' . $arr->uamip . ':' . $arr->uamport . '/logon?username=' . $arr->username_fast . '&response=' . $response . '&userurl=wicity.vn';
    }

    public function rediectAuth($param) {

        $_chal = $param->challenge;
        $hexchal = pack("H32", $_chal);
        $newchal = $param->uamsecret ? pack("H*", md5($hexchal . $param->uamsecret)) : $hexchal;
        $response = md5("\0" . $_GET['password'] . $newchal);

        $newpwd = pack("a32", $_GET['password']);
        $pappassword = implode('', unpack("H32", ($newpwd ^ $newchal)));

        print implode('', array(
            '<meta http-equiv="refresh" content="0;url=',
            'http://', $param->uamip, ':', $param->uamport, '/',
            'logon?username=', $_GET['username'], '&response=', $response,
            '&userurl=wicity.vn">'
        ));
    }

    public function display_success() {
        $landding_page = 'http://wicity.vn';
        if (!in_array($this->session->userdata('landing_page'), array('', null))) {
            $landding_page = $this->session->userdata('landing_page');
        }
        print "
            <html>
            <head>
    			 <script>
    			 window.location.href = '".$landding_page."'; 
    			 </script>
    		</head>
    		<body>
    		</body>
    		</html>";
    }

    public function display_failed($param) {
        //echo '<h1>Login failed :(</h1>';
        echo '
        <html>
        <head>
            <title>WICITY</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
            <meta name="apple-mobile-web-app-capable" content="yes">
            <meta name="apple-mobile-web-app-status-bar-style" content="black">
            <link rel="stylesheet" type="text/css" href="' . $this->data['baseurl'] . '/public/theme/campaign/css/style.css">
            <link rel="stylesheet" type="text/css" href="' . $this->data['baseurl'] . '/public/theme/campaign/ui-mobile/ui.css">
		</head>
		<body style="background: url()">
            <div class="ui-page">
                <div class="ui-header">
                    <div class="ui-logo">
                        <div class="logo">
    
                        </div>
                    </div>
                    <div class="ui-right header">
                        <div class="arrow"></div>
                        <div class="ui-title ui-text-bold">WICITY</div>
                    </div>
    
                </div>
                <div class="ui-body">
                    <div class="ui-block wrapper">
                        <div class="ui-empty-20"></div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-image ui-align-center"></div>
                        
                        <div class="ui-text-center ui-text-bold" style="color: #000;font-size:20px;">KẾT NỐI THẤT BẠI</div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-block ui-align-center ui-block-button">
                            <div class="ui-empty-10"></div>
                            <a class="ui-btn ui-btn-block ui-text-bold defined-font-size_15" style="background-color: #1a4793;border-top-right-radius: 12px;border-bottom-left-radius: 12px;border-top-left-radius: 0;border-bottom-right-radius: 0;" href="http://', $param->uamip, ':', $param->uamport, '/prelogin', "?userurl={$_GET['userurl']}", '"> KẾT NỐI LẠI </a>
                        </div>
                        
                        <div class="ui-empty-10"></div>
                    </div>
                </div>
            </div>
		</body>
		</html>
        ';
        /* print implode('', array(
          '<a href="http://', $param->uamip, ':', $param->uamport, '/prelogin', "?userurl={$_GET['userurl']}", '">',
          'Please try again',
          '</a>'
          )); */
    }

    public function display_already($param) {
        /*echo '<h1>Already logged in</h1>';
        print implode('', array(
            '<a href="http://', $param->uamip, ':', $param->uamport, '/logoff', '">',
            '    Login',
            '</a>'
        )); */
		echo '<html>
        <head>
            <title>WICITY - Already logged in</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
            <meta name="apple-mobile-web-app-capable" content="yes">
            <meta name="apple-mobile-web-app-status-bar-style" content="black">
            <link rel="stylesheet" type="text/css" href="' . $this->data['baseurl'] . '/public/theme/campaign/css/style.css">
            <link rel="stylesheet" type="text/css" href="' . $this->data['baseurl'] . '/public/theme/campaign/ui-mobile/ui.css">
		</head>
		<body style="background: url()">
            <div class="ui-page">
                <div class="ui-header">
                    <div class="ui-logo">
                        <div class="logo">
    
                        </div>
                    </div>
                    <div class="ui-right header">
                        <div class="arrow"></div>
                        <div class="ui-title ui-text-bold">WICITY</div>
                    </div>
                </div>
                <div class="ui-body">
                    <div class="ui-block wrapper">
                        <div class="ui-empty-20"></div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-image ui-align-center"></div>
                        
                        <div class="ui-text-center ui-text-bold" style="color: #000;font-size:20px;">KẾT NỐI THẤT BẠI</div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-block ui-align-center ui-block-button">
                            <div class="ui-empty-10"></div>
                            <a class="ui-btn ui-btn-block ui-text-bold defined-font-size_15" style="background-color: #1a4793;border-top-right-radius: 12px;border-bottom-left-radius: 12px;border-top-left-radius: 0;border-bottom-right-radius: 0;" href="http://', $param->uamip, ':', $param->uamport, '/prelogin', "?userurl={$_GET['userurl']}", '"> KẾT NỐI LẠI </a>
                        </div>
                        <div class="ui-empty-10"></div>
                    </div>
                </div>
            </div>
		</body>
		</html>';
    }

    public function display_logoff($param) {
        //echo '<h1>Logged out</h1>';
        echo ' <html>
        <head>
            <title>WICITY - Logged out</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
            <meta name="apple-mobile-web-app-capable" content="yes">
            <meta name="apple-mobile-web-app-status-bar-style" content="black">
            <link rel="stylesheet" type="text/css" href="' . $this->data['baseurl'] . '/public/theme/campaign/css/style.css">
            <link rel="stylesheet" type="text/css" href="' . $this->data['baseurl'] . '/public/theme/campaign/ui-mobile/ui.css">
		</head>
		<body style="background: url()">
            <div class="ui-page">
                <div class="ui-header">
                    <div class="ui-logo">
                        <div class="logo">
    
                        </div>
                    </div>
                    <div class="ui-right header">
                        <div class="arrow"></div>
                        <div class="ui-title ui-text-bold">WICITY</div>
                    </div>
                </div>
                <div class="ui-body">
                    <div class="ui-block wrapper">
                        <div class="ui-empty-20"></div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-image ui-align-center"></div>
                        
                        <div class="ui-text-center ui-text-bold" style="color: #000;font-size:20px;">KẾT NỐI THẤT BẠI</div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-empty-20"></div>
                        <div class="ui-block ui-align-center ui-block-button">
                            <div class="ui-empty-10"></div>
                            <a class="ui-btn ui-btn-block ui-text-bold defined-font-size_15" style="background-color: #1a4793;border-top-right-radius: 12px;border-bottom-left-radius: 12px;border-top-left-radius: 0;border-bottom-right-radius: 0;" href="http://', $param->uamip, ':', $param->uamport, '/prelogin', "?userurl={$_GET['userurl']}", '"> KẾT NỐI LẠI </a>
                        </div>
                        <div class="ui-empty-10"></div>
                    </div>
                </div>
            </div>
		</body>
		</html>';
    }
    
    public function savefile($base64_string,$paths,$nameimagess, $url_convert = 'd')
    {
        //die('32423');
        @mkdir($paths.'tmp', 0301);
        $ifp = fopen($paths.'tmp/'.$nameimagess, "wb" ); 
        fwrite( $ifp, base64_decode( $base64_string) ); 
        fclose( $ifp );
        //return $this->downloadPicture($paths, $this->data['baseurl'], $url_convert, $nameimagess);
        return ;
    }
    
   private function downloadPicture($imagesource, $base, $url_convert, $nameimagess)
    {
        $img_src = $imagesource.'tmp/'.$nameimagess;
        list($width, $height) = @getimagesize($img_src);
        $new_width = $width;
        $new_height = $height;
        if(in_array(@$width, array(null, '', '0')) || in_array(@$height, array(null, '', '0')))
        {
            @unlink($imagesource.'tmp/'.$nameimagess);
            return '201';
        }
        @$image_p = imagecreatetruecolor($new_width, $new_height);
        @$image = imagecreatefromjpeg($img_src);
        @imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        @imagejpeg($image_p, $imagesource.$nameimagess, 100);
        @unlink($imagesource.'tmp/'.$nameimagess);
        @imagedestroy($image);
        return '200';
    }
}
